package com.smartao.core.orm.mybatis;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MybatisPageHandler {

	private static MybatisPageHandler instance = new MybatisPageHandler();

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private MybatisPageHandler() {
	}

	/**
	 * 获取总数
	 * @param parameterHandler
	 * @param connection 
	 * @param originalSql sql语句
	 * @throws Exception
	 */
	public long getTotal(ParameterHandler parameterHandler, Connection connection, String originalSql) throws Exception {
		//TODO 缓存具有相同SQL语句和参数的总数
		String countSql = getCountSql(originalSql);
		PreparedStatement prepareStatement = connection.prepareStatement(countSql);
		parameterHandler.setParameters(prepareStatement);
		ResultSet rs = prepareStatement.executeQuery();
		int count = 0;
		if (rs.next()) {
			count = rs.getInt(1);
		}
		rs.close();
		prepareStatement.close();
		return count;
	}

	public String getCountSql(String originalSql) {
		String countSql = "SELECT COUNT(*) FROM(" + originalSql + ") AS TMP_TOTAL";
		if (logger.isDebugEnabled()) {
			logger.debug("总数SQL : " + countSql);
		}
		return countSql;
	}

	public static MybatisPageHandler getInstance() {
		return instance;
	}

}
